package com.atguigu.mybatisplus.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
//        实现填充业务逻辑
        log.info("insert 自动填充……");
        boolean hasCreateTime = metaObject.hasSetter("createTime");
        if (hasCreateTime){//进行属性填充之前先判断是否有这个属性
        this.strictInsertFill(metaObject,"createTime", LocalDateTime.class,LocalDateTime.now());
        }
        boolean hasUpdateTime = metaObject.hasSetter("updateTime");
        if (hasUpdateTime){
        this.strictInsertFill(metaObject,"updateTime", LocalDateTime.class,LocalDateTime.now());
        }
        Object age = this.getFieldValByName("age", metaObject);
        if (age==null){//如果业务层没有赋值，才进行自动填充
        log.info("insert age 属性");
        this.strictInsertFill(metaObject,"age",Integer.class,19);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("update 自动填充……");
        boolean hasUpdateTime = metaObject.hasSetter("updateTime");
        if (hasUpdateTime){
        this.strictUpdateFill(metaObject,"updateTime",LocalDateTime.class,LocalDateTime.now());
        }
    }
}
